﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using System.Threading;

namespace __moov
{
    public partial class FrmVerify : Form
    {
        Thread worker = null;
        bool isVerified = false;
        bool hasContact = false;
        String msisdn = null;
        String email = null;

        public FrmVerify(String msisdn, String email)
        {
            InitializeComponent();
            this.SetDesktopLocation(Screen.PrimaryScreen.WorkingArea.Right - this.Width - 60,
              Screen.PrimaryScreen.WorkingArea.Bottom - this.Height - 130);

            this.btnVerify.Enabled = false;
            this.msisdn = msisdn;
            this.email = email;
        }

        private void envBtnLinkAccClick(object sender, EventArgs e)
        {
            configureDevice();         
            //close all other form except the main form
            for (int index = Application.OpenForms.Count - 1; index >= 0; index--)
            {
                if (Application.OpenForms[index].Name != "frmMain")
                {
                    Application.OpenForms[index].Hide();
                }
            }

        }

        private void envBtnCloseClick(object sender, EventArgs e)
        {
            this.Close();
        }

        public void verifyUser(){

            String[] url = null;
            String[] urlParam = null;
            isVerified = false;

            this.Invoke((MethodInvoker)delegate
            {
                //Enable activation only when user verified
                this.btnVerify.Enabled = false;

                if (txtCode.Text == null || txtCode.Text == "CODE" || txtCode.Text.Length == 0) { this.pbCode.Image = null; return; }
                if (!System.Text.RegularExpressions.Regex.IsMatch(txtCode.Text, @"^[0-9]{4,15}$", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                {
                    this.pbCode.Image = Properties.Resources.deny;
                }

                //load while requesting from api service
                this.pbCode.Image = Properties.Resources.loading;

                url = new String[3];
                url[0] = Properties.Settings.Default.requestPartialURL;
                url[1] = "0";
                url[2] = "users/verification";

                urlParam = new String[5];
                urlParam[0] = "fields=user_id:id";
                urlParam[1] = "code="+txtCode.Text;
                urlParam[2] = "user_id=" + (String) Properties.Settings.Default.userId;
                urlParam[3] = "msisdn=" + (String) msisdn;
                urlParam[4] = "fmt=json";
            });

            try
            {
                if (url == null) { this.pbCode.Image = null; return; };
                //make request
                String uri = String.Join("/", url) + "?" + String.Join("&", urlParam);
                WebRequest webRequest = WebRequest.Create(uri);
                webRequest.Method = "POST";
                WebResponse webResponse = webRequest.GetResponse();

                //Prepare to read response
                StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
                string str = null;
                while ((str = responseReader.ReadLine()) != null)
                {
                    UsersPOCO[] apiUsersResponse = JsonConvert.DeserializeObject<UsersPOCO[]>(str);
                    foreach (UsersPOCO requestedUser in apiUsersResponse)
                    {
                        if (requestedUser.id != null)
                        {
                            if (requestedUser.status == "T")
                            {
                                Properties.Settings.Default.userId = requestedUser.id;
                                Properties.Settings.Default.accountStatus = true;
                                Properties.Settings.Default.networkUsage = "Manage";
                                Properties.Settings.Default.Session = (DateTime)DateTime.Now;
                                Properties.Settings.Default.useGPS = true;
                                Properties.Settings.Default.syncWithAccount = false;
                                Properties.Settings.Default.deviceAlias = requestedUser.device_name;
                                isVerified = true;
                            }
                        }
                    }
                }

                this.Invoke((MethodInvoker)delegate
                {
                    if (isVerified)
                    {                        
                        this.pbCode.Image = Properties.Resources.accept;
                        //Enable activation only when user exists
                        this.btnVerify.Enabled = true;
                    }
                    else this.pbCode.Image = Properties.Resources.deny;
                });


            }
            catch (Exception ex)
            {
                //write to event log
                System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
                appLog.Source = "Moov - Client";
                appLog.WriteEntry(ex.ToString());

                //clear the picture box
                this.Invoke((MethodInvoker)delegate
                {
                    this.pbCode.Image = null;
                });
            }
         
            return;

        }


        public void userSendToken()
        {

            String[] url = null;
            String[] urlParam = null;
            isVerified = false;

            //Enable activation only when user verified
            this.btnVerify.Enabled = false;

            url = new String[3];
            url[0] = Properties.Settings.Default.requestPartialURL;
            url[1] = "0";
            url[2] = "users/token_send";

            urlParam = new String[4];
            urlParam[0] = "fields=status";
            urlParam[1] = "user_id=" + (String)Properties.Settings.Default.userId;
            urlParam[2] = "msisdn=" + (String)msisdn;
            urlParam[3] = "fmt=json";
            

            try
            {                
                //make request
                String uri = String.Join("/", url) + "?" + String.Join("&", urlParam);
                WebRequest webRequest = WebRequest.Create(uri);
                webRequest.Method = "POST";
                WebResponse webResponse = webRequest.GetResponse();

                //Prepare to read response
                StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
                string str = null;
                while ((str = responseReader.ReadLine()) != null)
                {
                    UsersPOCO[] apiUsersResponse = JsonConvert.DeserializeObject<UsersPOCO[]>(str);
                    foreach (UsersPOCO requestedUser in apiUsersResponse)
                    {
                        if (requestedUser.status == null) MessageBox.Show("Could not send verification code");
                    }
                }



            }
            catch (Exception ex)
            {
                //write to event log
                System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
                appLog.Source = "Moov - Client";
                appLog.WriteEntry(ex.ToString());
            }

            return;

        }


        private void lnkReSendLinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            txtCode.Text = null;
            Thread worker = new Thread(userSendToken);
            worker.Start();
        }

        public void configureDevice()
        {

            String[] url = null;
            String[] urlParam = null;
            isVerified = false;

            url = new String[3];
            url[0] = Properties.Settings.Default.requestPartialURL;
            url[1] = Properties.Settings.Default.userId;
            url[2] = "contacts";

            urlParam = new String[5];
            urlParam[0] = "fields=id,name,device_id,email,msisdn";
            urlParam[1] = "user_id=" + (String) Properties.Settings.Default.userId;
            urlParam[3] = "func_fields=X";
            urlParam[4] = "fmt=json";
          
 
            try
            {
                //make request
                String uri = String.Join("/", url) + "?" + String.Join("&", urlParam);
                WebRequest webRequest = WebRequest.Create(uri);
                webRequest.Method = "GET";
                WebResponse webResponse = webRequest.GetResponse();

                //Prepare to read response
                StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
                string str = null;
                while ((str = responseReader.ReadLine()) != null)
                {
                    ContactsPOCO[] apiContactsResponse = JsonConvert.DeserializeObject<ContactsPOCO[]>(str);
                    foreach (ContactsPOCO requestedContact in apiContactsResponse)
                    {
                        if (requestedContact.id != null)
                        {
                            this.tblContactsTableAdapter1.Insert(requestedContact.name, requestedContact.msisdn,
                                requestedContact.email, requestedContact.device_id, requestedContact.device_name, requestedContact.location_name);

                            hasContact = true;
                            isVerified = true;
                        }
                    }
                }

                this.Invoke((MethodInvoker)delegate
                {
                    if (isVerified)
                    {
                        this.pbCode.Image = Properties.Resources.accept;
                        //Enable activation only when user exists
                        this.btnVerify.Enabled = true;
                    }
                    else this.pbCode.Image = Properties.Resources.deny;
                });


            }
            catch (Exception ex)
            {
                //write to event log
                System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
                appLog.Source = "Moov - Client";
                appLog.WriteEntry(ex.ToString());
            }

            if (hasContact)
            {
                frmMain frmmain = new frmMain();
                frmmain.Show();
            }
            else
            {
                frmWelcome frmwelcome = new frmWelcome();
                frmwelcome.Show();
            }

        }

        private void FrmVerifyLoad(object sender, EventArgs e)
        {
            Thread worker = new Thread(userSendToken);
            worker.Start();
        }

        private void txtCode_TextChanged(object sender, EventArgs e)
        {
            if (txtCode.Text.Length < 4) return;
            Thread worker = new Thread(verifyUser);
            worker.Start();
        }

        //private void tblContactsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        //{
        //    this.Validate();
        //    this.tblContactsBindingSource.EndEdit();
        //    this.tableAdapterManager.UpdateAll(this.moovDataSet);

        //}
    }
}
